<?php
/**
 * 物资分类
 */
namespace App\Http\Controllers\Api;
use App\Model\Company;
use App\Model\Goods;
use App\Model\MaterialList;
use App\Model\Stock;
use App\Model\Users;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use DB;
class GoodsController extends Controller
{
    /**
     * 物资分类列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function goodslistdata(Request $request)
    {
        //$query = $this->goodspub($request);
        $query= Goods::orderby('id','asc');
        $getPid=[];
        if(isset($request['name']) && $name=$request['name']){
            //$name = json_decode($request['name'],true);
            //$query = $query->where('name','like','%'.$name.'%');
            $getPid = Goods::getPidByName($name);
            if($name){
                //$query = $query->whereIn('id',$getPid);
                /*$cou = count($getPid);
                if($cou<4){
                    $pid = $getPid[0]??'';
                    $query = $query->orWhere('pid',$pid);
                }*/
                /*$query= $query->with(['children' => function($query) use ($getPid) {
                    $query->whereIn('id',$getPid);
                }]);*/
            }
        }/*else{
            $query= $query->with(['children']);
        }*/
        //$query= $query->where('pid', 0);
        $res=$query->get()->toArray();  //paginate($request->get('limit',15))
        $new_data = [];
        foreach ($res as $key => $value) {
            $new_data[$key]['id'] = $value['id'];
            $new_data[$key]['pid'] = $value['pid'];
            $new_data[$key]['name'] = $value['name'];
        }

        $res['data'] = Goods::sort_data($new_data,'id', 'pid',  'children',  0,  $getPid);
        //$res['data'] = Goods::removeEmptyValues($res['data']);
        if($getPid){
            $res['data'] = Goods::removeValues($res['data'],$getPid);
        }
        $res_arr['data']['list'] = $res['data'];
        $res_arr['data']['count'] = 0;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资分类列表跟导出公用
     * @param $request
     * @return array
     */
    public function goodspub($request){
        $query= Goods::orderby('id','asc')->with(['children'])
            ->where('pid', 0);
        if(isset($request['name'])){
            $name = json_decode($request['name'],true);
            //$query = $query->where('name','like','%'.$name.'%');
            if($name){
                $query = $query->whereIn('id',$name);
            }
        }
        return $query;
    }

    /**
     * 导出物资分类pdf url
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function downloadUrl(Request $request)
    {
        $date=time();
        $filename = '物资分类列表-'.$date;
        $file_name = $filename.".pdf";
        $file_url = "http://www.beizhainew.com/word/template/GBT38565-2020.pdf";
        header("Content-type:application/pdf");
        header("Content-Disposition:attachment;filename=$file_name");
        readfile($file_url);
    }

    /**
     * 导出物资名称列表
     * @param Request $request
     * @return void
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \PHPExcel_Writer_Exception
     */
    public function exportone(Request $request)
    {
        $path = '/word/template/GBT38565-2020.pdf';
        $date=time();
        $filename = '物资分类列表-'.$date;
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].'/admin/goods/downloadUrl','file_name'=>$filename]);  //'http://'.$_SERVER['HTTP_HOST'].$path
        die;
        //$query = $this->goodspub($request);
        $query= Goods::orderby('id','asc');
        if(isset($request['name']) && $name = $request['name']){
            $query = $query->where('name','like','%'.$name.'%');
        }
        $dataExpor= $query->get()->toArray();

        $excel = new \PHPExcel();
        $excel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objActSheet = $excel->getActiveSheet();
        $letter = array('A','B');  //,'C','D','E','F'
        $title = [
            'A1'=>'代 码',
            'B1'=>'名 称',
            /*'C1'=>'入库数量',
            'D1'=>'库存数量',
            'E1'=>'出库数量',
            'F1'=>'损耗数量',*/
        ];
        foreach ($title as $tk=>$tv){
            $objActSheet->setCellValue($tk,$tv);
        }

        foreach ($letter as $l){
            $objActSheet->getStyle($l.'1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
        }

        /**填充内容*/
        $orirow = 2;
        $i = 1;

        foreach ($dataExpor as &$val) {
            $objActSheet->setCellValue("A".$orirow,$val['code']??'');
            $str = $val['name']??'';
            if($val['laravel']==3){
                $str=' '.$val['name']??'';
            }else if($val['laravel']==4){
                $str='  '.$val['name']??'';
            }
            $objActSheet->setCellValue("B".$orirow,$str);
            /*$objActSheet->setCellValue("C".$orirow,$val['income_warehouse']??'');
            $objActSheet->setCellValue("D".$orirow,$val['warehouse']??'');
            $objActSheet->setCellValue("E".$orirow,$val['leave_warehouse']??'');
            $objActSheet->setCellValue("F".$orirow,$val['loss_warehouse']??'');*/

            $i ++;
            $orirow ++;

        }
        /**填充内容*/
        //统一设置填充内容左右居中、字号、宽度
        foreach ($letter as $l){
            for ($x = 2;$x<=$orirow;$x++){
                /*$objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中
                $objActSheet->getStyle($l.'2')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);//左右居中*/
                if($l=='A'){
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_CENTER;
                }else{
                    $setHorizontal = \PHPExcel_Style_Alignment::HORIZONTAL_LEFT;
                }
                $objActSheet->getStyle($l.$x)->getAlignment()->setHorizontal($setHorizontal);
                $objActSheet->getStyle($l.$x)->getFont()->setSize(10);
                $objActSheet->getColumnDimension($l)->setWidth(40);

            }

        }
        /*$objActSheet->getColumnDimension('B')->setWidth(50);
        $objActSheet->getColumnDimension('C')->setWidth(50);
        $objActSheet->getColumnDimension('J')->setWidth(50);*/
        for ($x=1; $x<=($orirow); $x++) {
            $objActSheet->getRowDimension($x)->setRowHeight(30);//统一设置行高度

        }
        $styleArray = array(
            'borders' => array(
                'allborders' => array(
                    'style' => \PHPExcel_Style_Border::BORDER_THIN,//细边框
                ),
            ),
        );
        $objActSheet->getStyle('A1:B1'.($orirow))->applyFromArray($styleArray);//设置粗边框


        $write = new \PHPExcel_Writer_Excel5($excel);
        ob_end_clean();
        //$date = Carbon::now()->toDateString();//表名前缀日期
        $date=time();
        $filename = '物资分类列表-'.$date;
        $path = '/storage/excel/'.$filename.'.xls';
        $res = $write->save(public_path().$path);
        return response()->json(['code'=>0,'msg'=>'导出成功','url'=>'http://'.$_SERVER['HTTP_HOST'].$path,'file_name'=>$filename]);
    }

    /**
     * 物资分类修改页面
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function referweb(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;
        if($id){
            $data = Goods::where('id',$id)->first();
            if(empty($data)){
                $res_arr["code"] = 408;
                $res_arr["message"] = '该分类不存在，请联系管理员';
                return response()->json($res_arr);
            }
        }else{
            $data = Goods::select(DB::raw('SUM(`income_warehouse`) as income_warehouse,SUM(`leave_warehouse`) as leave_warehouse,SUM(`loss_warehouse`) as loss_warehouse,SUM(`warehouse`) as warehouse'))->first();
        }


        $res_arr['data'] = $data;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资分类数据处理
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function goodsdo(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $name = isset($redata['name']) ? $redata['name'] : '';
        $data = Goods::where('id',$id)->first();
        unset($redata['_token']);
        $name_data = Goods::where('name',$name)->first();
        if(empty($name)){
            $res_arr["code"] = 408;
            $res_arr["message"] = '名称不能为空，请重新录入';
            return response()->json($res_arr);
        }
        if($data){
            if($name_data && $name_data['id']!=$id){
                $res_arr["code"] = 408;
                $res_arr["message"] = '该名称已存在，请重新录入';
                return response()->json($res_arr);
            }
            $res = Goods::where('id', $id)->update($redata);
        }else{
            if($name_data){
                $res_arr["code"] = 408;
                $res_arr["message"] = '该名称已存在，请重新录入';
                return response()->json($res_arr);
            }
            unset($redata['id']);
            $user = Auth::user();
            $userid = $user->id;
            $redata['user_id'] = $userid;
            $redata['created_at'] = date('Y-m-d H:i:s');
            $res = Goods::insertGetId($redata);
        }
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资分类数据删除
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function goodsdelete(Request $request)
    {
        $redata = $request->all();
        $id = isset($redata['id']) ? $redata['id'] : 0;
        $data = Goods::where('id',$id)->first();
        $materialList_data = MaterialList::where('goods_id',$id)->first();
        if($materialList_data){
            $res_arr["code"] = 408;
            $res_arr["message"] = '该分类已被使用，不能删除';
            return response()->json($res_arr);
        }
        if($data['income_warehouse']!=0 || $data['leave_warehouse']!=0 || $data['loss_warehouse']!=0 || $data['warehouse']!=0){
            $res_arr["code"] = 408;
            $res_arr["message"] = '只有入库、出库、在库、损耗数量均为0时才可删除物资分类';
            return response()->json($res_arr);
        }
        $resu = Goods::where('id', $id)->delete();
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资分类列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function goods_all(Request $request)
    {
        $goods = Goods::with(['children'])
            ->where('pid', 0)->get()->toarray();  //select('id','name')->
        $res_arr['data'] = $goods;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 物资分类列表数据操作
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function goods_all_app(Request $request)
    {
        $goods = Goods::with(['materialList:id,goods_id,name'])->select('id','name','pid')->get()->toarray();
        $new_data = [];
        foreach ($goods as $key => $value) {
            $new_data[$key]['id'] = $value['id'];
            $new_data[$key]['pid'] = $value['pid'];
            $new_data[$key]['name'] = $value['name'];
            $new_data[$key]['material_list'] = $value['material_list'];
        }
        $tree = Goods::sort_data($new_data,'id');
        $res_arr['data'] = $tree;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }

    /**
     * 库存管理页面的库存数
     * @param Request $quest
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Foundation\Application|\Illuminate\View\View
     */
    public function getcount(Request $request)
    {
        //修改的话该值有值
        $id = isset($request['id']) ? $request['id'] : 0;
        $checkcategory_id = isset($request['checkcategory_id']) ? $request['checkcategory_id'] : 0;
        $name = isset($request['name']) ? $request['name'] : 0;
        $id = isset($request['id']) ? $request['id'] : 0;
        $companys = Company::select('id','comName','address');
        $user = Auth::user();
        $role = $user->role;
        $community = $user->community;

        $data = Stock::select(DB::raw('SUM(`income_warehouse`) as income_warehouse,SUM(`leave_warehouse`) as leave_warehouse,SUM(`loss_warehouse`) as loss_warehouse,SUM(`warehouse`) as warehouse'));
        if(Users::iscommunity($role)){
            $companys = $companys->where('community',$community);
            $companys = $companys->get()->toArray(); //单位名称
            $companyid_arr = array_column($companys,'id');
            $data = $data->whereIn('company_id',$companyid_arr);
        }

        if($id){
            $data = $data->where('goods_id',$id);
        }
        if($checkcategory_id){
            $data = $data->where('checkcategory_id',$checkcategory_id);
        }
        if($name){
            $materialList = MaterialList::where('name','like','%'.$name.'%')->get()->toarray();
            $material_ids = array_column($materialList,'id');
            $data = $data->whereIn('material_id',$material_ids);
        }
        $data = $data->first();

        $res_arr['data'] = $data;
        $res_arr["code"] = 200;
        $res_arr["message"] = 'success';
        return response()->json($res_arr);
    }
}
